package xginplus

import (
	"bytes"
	"crypto/md5"
	"fmt"
	"io"
	"sync"
	"time"
)

// 结果缓存
var _jitter_cache sync.Map = sync.Map{}

// 获取缓存下标
func (c *Context) keys() string {
	dat, err := c.GetRawData()
	if err != nil {
		return ""
	}
	// 将数据再次写回请求体中，避免启用抖动后无法获取数据问题
	c.Request.Body = io.NopCloser(bytes.NewBuffer(dat))
	uri := c.Request.Method + ":" + c.Request.RequestURI + ";ip " + c.ClientIP() + ";ua " + c.Request.UserAgent() + ";pm " + string(dat) + ";ct " + c.ContentType()
	b := md5.Sum([]byte(uri))
	key := fmt.Sprintf("%x", b)
	return key
}

// 获取是否为重复请求
func (c *Context) hasJ() (any, bool) {
	k := c.keys()
	for !cnt_lock.Lock(k) {
		time.Sleep(time.Microsecond * 10) // 休眠0.01毫秒，避免一直检测消耗资源
		break
	}
	v, ok := _jitter_cache.Load(k)
	return v, ok
}

// 获取是否为重复请求
//
//	v	设置的值
func (c *Context) setJ(v any) {
	k := c.keys()
	_jitter_cache.Store(k, v)
	cnt_lock.UnLock(k)
	go func(k string, ts time.Duration) {
		if ts <= 0 {
			ts = time.Second
		}
		time.Sleep(ts)
		_jitter_cache.Delete(k)
	}(k, c.JitterTime)
}
